import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/LoginComponent.vue'
import Home from '../components/HomeComponent.vue'
import Welcome from '../components/WelcomeComponent.vue'
import Users from '../components/user/UsersComponent.vue'
import GoodsList from '../components/goods/ListComponent.vue'
import Orders from '../components/order/OrdersComponent.vue'
import Score from '../components/score/ScoreListComponent.vue'
import Exchange from '../components/score/ScoreExchangeComponent.vue'
import Pays from '../components/pay/PayListComponent.vue'
import Coupon from '../components/coupon/CouponComponent.vue'
import AddGoods from '../components/goods/AddGoodsComponent.vue'
import AfterSell from '../components/after/AfterSellComponent.vue'
import Enjoy from '../components/enjoy/EnjoyComponent.vue'
import AddEnjoy from '../components/enjoy/AddEnjoyComponent.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    redirect: '/login' // 路由重定向
  },
  {
    path: '/login',
    name: 'login',
    component: Login
  },
  {
    path: '/home',
    name: 'home',
    component: Home,
    redirect: '/welcome',
    children: [
      {
        path: '/welcome',
        component: Welcome
      },
      {
        path: '/users',
        component: Users
      },
      {
        path: '/goods',
        component: GoodsList
      },
      {
        path: '/addGoods',
        component: AddGoods
      },
      {
        path: '/orders',
        component: Orders
      },

      {
        path: '/pays',
        component: Pays
      },
      {
        path: '/score',
        component: Score
      },
      {
        path: '/scoreExchange',
        component: Exchange
      },
      {
        path: '/coupon',
        component: Coupon
      },
      {
        path: '/afterSell',
        component: AfterSell
      },
      {
        path: '/enjoy',
        component: Enjoy
      },
      {
        path: '/addEnjoy',
        component: AddEnjoy
      }
    ]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to 将要访问的路径
  // from 代表从哪个路径跳转而来
  // next 是一个函数， 表示放行
  // 1. next（） 放行  2. next('/login') 强制跳转到login

  if (to.path === '/login') return next()
  // 先获取 token
  const tokenStr = localStorage.getItem('token')
  if (!tokenStr) return next('/login')
  // token存在时，直接放行
  next()
})

export default router
